package com.atguigu.java2;

/**
 * 生产者消费者问题
 */
public class ProductTest {

    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producter producter = new Producter(clerk);
        Consumer consumer = new Consumer(clerk);

        Thread t1 = new Thread(producter);
        Thread t2 = new Thread(consumer);

        t1.setName("生产者1");
        t2.setName("消费者1");

        t1.start();
        t2.start();
    }



}

class Clerk {
    private int num;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public synchronized void addNum() {
        if (num < 20) {
            System.out.println(Thread.currentThread().getName() + "---生产产品的数量：" + num);
            num++;
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void reduceNum() {
        if (num > 0) {
            System.out.println(Thread.currentThread().getName() + "---消费产品的数量：" + num);
            num--;
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


class Producter implements Runnable {

    private Clerk clerk;

    public Producter(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            clerk.addNum();
        }

    }
}

class Consumer implements Runnable {

    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            clerk.reduceNum();
        }

    }
}


